import { type FunctionalComponent as FC, reactive, ref } from 'vue';
import * as Types from '@/store/modules/projectDetail/type';
import * as Api from '@/api/project/project';
import * as ApiTypes from '@/api/project/project.d';
import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
import Dialog from '@/components/dialog/index.vue';
import Table from '@/components/table/index.vue';
import '../styles/second.less';
import useUtils from "@/views/dimensioning/project/hooks/useUtils";
import moment from "moment";
import _ from "lodash";

interface Prop {
  id: string;
  layout: string;
  status: string;
  type: string;
  disabled: boolean;
  form: Types.ViewDataSetting;
  commonList: ApiTypes.CommonConfigResponse;
  compList: ApiTypes.CompConfigItem[];
  toolList: ApiTypes.ToolConfigItem[];
  tableData: any[]; //添加的数据
  token: string;
}
const token = getToken();

const {  AnnoResultTypeEnum } = useUtils();

//下载模板
const download = () => {
  const a = document.createElement('a');
  const url = '/static/序列导入模板.xlsx';
  a.href = url;
  a.download = '序列导入模板.xlsx';
  a.click();
};
//一键清空
const delAll = (props: Prop) => {
  // @ts-ignore
  props.form.seriesList = [];
  Message.success('已删除');
};
//单个删除
const del = (index, props) => {
  props.form.seriesList.splice(index, 1);
  Message.success('已删除');
};
//上传序列
const loading = ref(false)
const onSuccess = async(res, props) => {
  const { code, data, msg } = res.response;
  if (code === 200) {
    addTableData(data.seriesInfoList, props);
  } else {
    Message.error(msg);
  }
  loading.value = false
}
const onBeforeUpload = () => {
  console.log('before upload')
  loading.value = true
  return true
}
const onError = () => {
  loading.value = false
  Message.error("上传失败");
}
const addTableData = (seriesInfoList, props) => {
  let added:number = 0; //新增
  let repeat:number = 0; //重复
  //对表格数据去重
  seriesInfoList.forEach((item:any)=> {
    const exist = props.form.seriesList.find((subItem: any)=> subItem.seriesUid === item.seriesUid);
    if(exist){
      repeat++
    }else{
      added++
      props.form.seriesList.push(item);
    }
  });
  Message.info({
    closable: true,
    content: `新增${added}个、重复${repeat}个(未导入)`,
    duration: 5000,
  });
}
//导入的下拉选项
const importDp = {
  content: () => (
    <>
      <a-doption onClick={importAnnoResult}>导入标注结果</a-doption>
      <a-doption onClick={viewAnnoResult}>查看已导入标注结果</a-doption>
    </>
  ),
};
//----------------导入标注结果
let importModalShow = ref(false); //导入标注结果弹框显示状态
//导入标注结果按钮
const importAnnoResult = () => {
  importModalShow.value = true;
  importFormRef.value.resetFields()
  importForm.value.file?.splice(0)
};
const importForm = ref({ taskId: 0, resultType: '', file: [] });
const uploadRef = ref();
const importFormRef = ref();
//弹框导入按钮处理
const handleImport = async (callback, props) => {
  importForm.value.taskId = +props.id
  console.log('importForm', importForm);
  console.log('uploadRef', uploadRef);
  console.log('importFormRef', importFormRef);
  if (callback.status === 'save') {//确定
    // 表单验证
    const valid = await importFormRef.value.validate()
    if(valid === undefined){//验证通过

    }else{//不通过
      callback.done(true)
      return false//阻止关闭弹框
    }
    // await new Promise((resolve) => setTimeout(resolve, 3000));
    //import api
    const formData = new FormData()
    // @ts-ignore
    formData.append("taskId", importForm.value.taskId)
    formData.append("resultType",importForm.value.resultType)
    const fileList = importForm.value.file || []
    // @ts-ignore
    formData.append("file", (fileList.length === 0)? null : fileList[0].file)
    const res:any = await Api.importAnnoData(formData)
    if(res.code === 200){
      Message.success("导入成功")
      callback.done(true)
    }else{
      Message.error("导入失败")
      callback.done(true)
      return false//阻止关闭弹框
    }
  } else if (callback.status === 'clear') {
    //取消
  }
  importFormRef.value.resetFields()
  importForm.value.file?.splice(0)
  // uploadRef.value.fileList = []
  importModalShow.value = false;//关闭弹框
};
const onChange = (fileList) => {
  // console.log("fileList", fileList, importForm.value.file)
  // importForm.value.file = (fileList.length === 0)? null : fileList[0].file;
};
//----------------查看导入结果
let resultModalShow = ref(false); //查看标注结果弹框显示状态
//查看已导入标注结果按钮
const viewAnnoResult = async (props) => {
  resultModalShow.value = true;
  // query api
  const res = await Api.getImportAnnoData({taskId: +props.id})
  if(res.code === 200){
    importData.tableData = res.data.list
  }else{
    Message.info("未查到结果")
  }

};
const importColumns:any = [
  { title: '导入人ID', dataIndex: 'userId' },
  { title: '导入时间', dataIndex: 'createTime', slotName: 'createTime', width: 200 },
  { title: '结果类型', dataIndex: 'importType', slotName: 'importType' },
  { title: '总序列数', dataIndex: 'seriesCount' },
  { title: '总结果数', dataIndex: 'resultCount' },
];
const importData:any = reactive({
  tableData:[
  /*{ userId: '1', createTime: '1', importType: '1', seriesCount: '1', resultCount: '1' }*/
  ]
});
const hideView = () => {
  resultModalShow.value = false;
};
//---------------------序列列表
const tableColumns = [
  { title: '序号', dataIndex: 'index', slotName: 'index', width: 80 },
  { title: '序列号', dataIndex: 'seriesUid', minWidth: 200, ellipsis: true },
  { title: '检查机型', dataIndex: 'modality', width: 100, ellipsis: true },
  { title: '部位', dataIndex: 'bodyPart', width: 100, ellipsis: true },
  { title: '文件类型', dataIndex: 'fileType', width: 100, ellipsis: true },
  {
    title: '标注结果',
    dataIndex: 'refResultTaskId',
    slotName: 'refResultTaskId',
    minWidth: 100,
  },
  { title: '操作', dataIndex: 'action', slotName: 'action', width: 100 },
];
const getOptions = (data) => {
  return data.map((item) => (
    <a-option value={item.value}>{item.name}</a-option>
  ));
};
const asyncFlag = ref(false)
const asyncAnno = (props,selectedId) => {
  //todo 关闭下拉
  if(!asyncFlag.value) return//列表选项不同步
  //把当前值赋给其他行
  props.form.seriesList.map(it => {
    if(selectedId === -1){
      it.refResultTaskId = -1
    }else if(it.taskRefList && it.taskRefList.find(item => item.taskId === selectedId)){//有的再赋值
      it.refResultTaskId = selectedId
    }
  })
}
const handleAnnoChange = (e) => {
  e.preventDefault()
}

const SecondStep: FC<Prop, any> = (props, ctx) => {
  /*console.log('form', props.form);
  props.form.seriesList.push({
    "bodyPart": "WOMB",
    "fileType": "BIG_IMAGE",
    "modality": "PATHOLOGY",
    "refResultTaskId": 238,
    "seriesUid": "a73d3fb9457d743ec807b2a25519e53013f4ed9d",
    taskRefList:[{taskId:238},{taskId: 11},{taskId: 22}]
  })*/
  return (
    <div class="second-form">
      <div class="header">
        <span class="title">序列列表</span>
        <div class="handle-bottom">
          <a-dropdown position="br" trigger="hover" v-slots={{
            content: () => (
                <>
                  <a-doption onClick={importAnnoResult} style={{justifyContent:'left'}}>导入标注结果</a-doption>
                  <a-doption onClick={()=>{viewAnnoResult(props)}}>查看已导入标注结果</a-doption>
                </>
            ),
          }}>
            <a-button size="small">
              <icon-import />
              &nbsp;导入
            </a-button>
          </a-dropdown>
          <a-button size="small" onClick={download}>
            <icon-download />
            &nbsp;下载上传模版
          </a-button>
          <a-button size="small" disabled={props.disabled} onClick={() => delAll(props)}>
            <icon-delete />
            &nbsp;一键清空
          </a-button>
          <a-upload
            accept=".xlsx"
            action="/api/anno/task/series/import"
            data={props.id && { taskId: props.id }}
            headers={{ 'x-auth-token': token }}
            show-file-list={false}
            disabled={props.disabled}
            style={{ display: 'inline-flex', width: 'auto' }}
            onSuccess={(res)=>onSuccess(res, props)}
            onBeforeUpload={onBeforeUpload}
            onError={onError}
          >
            {{
              'upload-button': () => (
                <a-button size="small" type="primary">
                  <icon-upload />
                  <>&nbsp;上传影像序列</>
                </a-button>
              ),
            }}
          </a-upload>
        </div>
      </div>
      <div class="table-content">
        <Table
          columns={tableColumns}
          data={props.form.seriesList}
          stickyHeader={true}
          showPageSize={false}
          showPagination={false}
          scroll={{ y: '100%' }}
          scrollbar={true}
          loading={loading.value}
          v-slots={{
            index: ({ record, column, rowIndex }) => (
              <span>{rowIndex + 1}</span>
            ),
            seriesUid: ({ record, column, rowIndex }) => {
              record.seriesUid;
            },
            refResultTaskId: ({ record, column, rowIndex }) => (
              <>
                <a-select
                  v-model={record.refResultTaskId}
                  onChange={handleAnnoChange}
                  disabled={props.disabled}
                  v-slots={{
                    footer: () => (
                      <div style={{display:'flex',justifyContent:'space-between',padding:'2px 5px'}}>
                        <a-checkbox v-model={asyncFlag.value}>列表选项同步</a-checkbox>
                        <a-button
                            type="primary"
                            size="small"
                            onClick={()=>{asyncAnno(props, record.refResultTaskId)}}
                        >确定</a-button>
                      </div>
                    )
                  }}
                >
                  {
                    [{taskId: -1, label: '不引用'}].concat(_.cloneDeep(record.taskRefList).map(it => {
                      it.label = it.taskId
                      return it
                    })).map((item) => (
                      <a-option value={item.taskId}>
                        {item.label}
                      </a-option>
                    ))
                  }
                </a-select>
              </>
            ),
            action: ({ record, column, rowIndex }) => (
              <a-button type="text" disabled={props.disabled} onClick={() => del(rowIndex, props)}>
                删除
              </a-button>
            ),
          }}
        ></Table>
      </div>
      <Dialog
        modal-class="secondStep-import-dialog"
        visible={importModalShow.value}
        title="导入标注结果"
        width={780}
        isForm={true}
        maskClosable={true}
        okText="导入"
        onUpdate:visible={(callback)=>{handleImport(callback, props)}}
      >
        {{
          default: () => (
            <>
              <a-form
                ref={importFormRef}
                model={importForm.value}
                disabled={props.disabled}
                auto-label-width
              >
                <a-form-item
                  field="resultType"
                  label="标注结果类型"
                  required
                  rules={[
                    { required: true, type: 'string', message: '请选择类型' },
                  ]}
                  validate-trigger={['change', 'input', 'blur']}
                >
                  <a-select
                    v-model={importForm.value.resultType}
                    placeholder="请选择"
                    style={{ width: '200px' }}
                  >
                    {
                      Object.entries(AnnoResultTypeEnum).map(([key, value]) => (
                        <a-option value={key}>{value}</a-option>
                      ))
                    }
                  </a-select>
                </a-form-item>
                <a-form-item
                  field="file"
                  label="指定上传文件"
                  wrapper-col-style={{textAlign: 'left'}}
                  required
                  rules={[
                    {
                      required: true,
                      type: 'string',
                      message: '请选择上传文件',
                    },
                  ]}
                  validate-trigger={['change']}
                >
                  <a-upload
                    v-model:file-list={importForm.value.file}
                    action="/"
                    accept=".csv"
                    limit={1}
                    headers={{ 'x-auth-token': token }}
                    auto-upload={false}
                    onChange={onChange}
                    ref={uploadRef}
                  >
                    {{
                      'upload-button': () => (
                        <>
                          <a-button>浏览</a-button>
                        </>
                      ),
                    }}
                  </a-upload>
                </a-form-item>
              </a-form>
            </>
          ),
        }}
      </Dialog>
      <Dialog
        modal-class="secondStep-viewImport-dialog"
        visible={resultModalShow.value}
        title="查看已导入标注结果"
        width={780}
        maskClosable={true}
        footer={false}
        onUpdate:visible={hideView}
      >
        {{
          default: () => (
            <Table
              columns={importColumns}
              data={importData.tableData}
              stickyHeader={true}
              showPageSize={false}
              showPagination={false}
              scroll={{ y: 300 }}
              scrollbar={true}
              v-slots={{
                createTime: ({ record, column, rowIndex }) => (
                    <>{ moment(record.createTime).format('YYYY-MM-DD hh:mm:ss') }</>
                ),
                importType: ({ record, column, rowIndex }) => (
                    <>{ AnnoResultTypeEnum[record.importType]}</>
                )
              }}
            ></Table>
          ),
        }}
      </Dialog>
    </div>
  );
};

export default SecondStep;
